var express = require('express');
var router = express.Router();


// 引入mysql的Query
const Query = require("../tools/db")

// 引入公共数据
const { api_url } = require("../config/config.js")




/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: '小u课堂api' });
});


// 首页的轮播图banners
router.get("/banners", async (req, res, next) => {

  // 请求数据库数据
  // let [err,result] = await Query(`select *  from e_banners`)
  let sql = `select id, 
                  CONCAT("${api_url}","/uploads/",image_src) as image_src,
                  title  
            from e_banners 
            where isshow=1`
  let [err, result] = await Query(sql)


  // 判断
  if (err) {
    next("服务器出错了，banners请求失败，请稍后再试")
    return
  }

  res.send({
    status: 200,
    msg: "banners请求成功",
    result
  })

})


// 首页的同步课程和精品课程
router.get("/courses", async (req, res, next) => {
  // 我们期望前端传递一个参数：type=1 同步  type=2 精品 
  let {type}=req.query

/*if(!type){
    next("请传递type参数，1是同步课程，2是精品课程")
    return
  }

  if(type!=2||type!=1){
    next("参数错误，type的值为1或2")
  } */
 

  if(!type || (type!=2 && type!=1) ){
    console.log(type);
    next("请传递正确type参数，1是同步课程，2是精品课程")
    return
  }


  // let sql = `select *  from  e_course where type=${type}`

  let sql = `select  id,
                     cid,
                     type,
                     title,
                     price,
                     concat("${api_url}","/uploads/","index/",image_src) as image_src,
                     type_name,
                     area_name,
                     subject_name
    from  e_course where type=${type}`

  let [err, result] = await Query(sql)

  if(err){
    next(`${type==1?"同步":"精品"}课程请求失败`)
    return
  }
  
  res.send({
    status:200,
    msg:`${type==1?"同步":"精品"}课程请求成功`,
    result
  })

})




module.exports = router;
